﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Data;
using DataAccess;

namespace iEN.Immediate
{
    public partial class ShowNowBuilding : System.Web.UI.Page
    {

        DataAccess.WebService WSAPI = new DataAccess.WebService();

        DataAccess.DBAccess DBAPI = new DataAccess.DBAccess();
        protected void Page_Load(object sender, EventArgs e)
        {
            
            if (this.Page.Request.QueryString["ID"] != null)
            {
                string strID = this.Page.Request.QueryString["ID"];

                //Create the Row
                //GridViewRow row = new GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal);
                ////Add the two Columns
                //row.Cells.AddRange(CreateCells());
                //gvMain.Parent.Controls.Add(row);

                if (strID == "-1")
                    strID = "0";


                DataTable dtOrg = DBAPI.getOrgGroupTable("1");

                Session["dtOrg"] = dtOrg;

                DataTable dtBuilding = dtOrg.Copy();

                dtOrg.DefaultView.RowFilter = "_parent_id ='" + strID + "'";
                dtOrg = dtOrg.DefaultView.ToTable();

                dtBuilding.DefaultView.RowFilter = "_id ='" + strID + "'";
                dtBuilding = dtBuilding.DefaultView.ToTable();

                if (dtBuilding.Rows.Count > 0)
                    Panel1.GroupingText = dtBuilding.Rows[0]["_name"].ToString();

                if (dtOrg.Rows.Count < 1)
                {
                    lblMsg.Visible = true;
                    lblMsg.Text = "無任何樓層";
                }

                else
                {
                    lblMsg.Visible = false;
                    Table tbMain = new Table();
                    int iRow = (dtOrg.Rows.Count / 5) + 1;
                    int iMod = dtOrg.Rows.Count % 5;
                    for (int i = 1; i <= iRow; i++)
                    {
                        if (i == iRow)
                        {
                            TableRow tbrM1 = new TableRow();

                            for (int j = 0; j < iMod; j++)
                            {
                                tbrM1.Cells.Add(CreateCells(dtOrg.Rows[(i - 1) * 5 + j]["_id"].ToString(), i, j));
                            }
                            tbMain.Rows.Add(tbrM1);

                        }
                        else
                        {
                            TableRow tbrM1 = new TableRow();

                            for (int j = 0; j < 5; j++)
                            {
                                tbrM1.Cells.Add(CreateCells(dtOrg.Rows[(i - 1) * 5 + j]["_id"].ToString(), i, j));
                            }
                            tbMain.Rows.Add(tbrM1);
                        }
                    }
                    Panel1.Controls.Add(tbMain);
                }


            }
        }

        private TableCell CreateCells(string strID, int i, int j)
        {

            DataTable dtOrg = (DataTable)Session["dtOrg"];

            dtOrg.DefaultView.RowFilter = "_id ='" + strID + "'";
            DataTable dtFloor = dtOrg.DefaultView.ToTable();

            //dtOrg.DefaultView.RowFilter = "_parent_id ='" + strID + "'";
            //DataTable dtFloor = dtOrg.DefaultView.ToTable();

            DataTable dtDevice = DBAPI.getDeviceTable("1");

            int iRoomCnt = 0;
            int iMeter = 0;

            dtOrg.DefaultView.RowFilter = "_parent_id ='" + dtFloor.Rows[0]["_id"].ToString() + "'";
            DataTable dtRoom = dtOrg.DefaultView.ToTable();
            iRoomCnt = dtRoom.Rows.Count;


                for (int n = 0; n < dtRoom.Rows.Count; n++)
                {
                    DataTable dtMeter = dtDevice.Copy();
                    dtMeter.DefaultView.RowFilter = "_org_group_id ='" + dtRoom.Rows[n]["_id"].ToString() + "'";
                    dtMeter = dtMeter.DefaultView.ToTable();
                    iMeter = iMeter + dtMeter.Rows.Count;
                }

            TableCell cell = new TableCell();

            Label lbFloor = new Label();
            lbFloor.Text = dtFloor.Rows[0]["_name"].ToString();
            Label lbRoom = new Label();
            lbRoom.Text = "寢室數 : " + iRoomCnt;
            Label lbMeter = new Label();
            lbMeter.Text = "電表數 : " + iMeter;
            Button btnSynBuilding = new Button();
            btnSynBuilding.Text = "樓層電表歸零";
            btnSynBuilding.Click += new System.EventHandler(this.btnClick);
            btnSynBuilding.CommandArgument = strID + "," + i + "," + j;

            Table tb1 = new Table();
            tb1.Width = 140;

            TableRow tbr1 = new TableRow();
            tbr1.BackColor = Color.LightSkyBlue;
            TableRow tbr2 = new TableRow();
            TableRow tbr3 = new TableRow();
            TableRow tbr4 = new TableRow();

            TableCell tbc1 = new TableCell();
            tbc1.Controls.Add(lbFloor);
            tbc1.HorizontalAlign = HorizontalAlign.Center;
            TableCell tbc2 = new TableCell();
            tbc2.Controls.Add(lbRoom);
            TableCell tbc3 = new TableCell();
            tbc3.Controls.Add(lbMeter);
            TableCell tbc4 = new TableCell();
            tbc4.Controls.Add(btnSynBuilding);
            tbc4.HorizontalAlign = HorizontalAlign.Center;

            tbr1.Cells.Add(tbc1);
            tbr2.Cells.Add(tbc2);
            tbr3.Cells.Add(tbc3);
            tbr4.Cells.Add(tbc4);

            tb1.Rows.Add(tbr1);
            tb1.Rows.Add(tbr2);
            tb1.Rows.Add(tbr3);
            tb1.Rows.Add(tbr4);

            tb1.BorderWidth = 2;

            cell.Controls.Add(tb1);

            return cell;
        }

        private void btnClick(object sender, System.EventArgs e)
        {
            divComfirm.Visible = true;
            Button btnSender = (Button)sender;
            string strArg = btnSender.CommandArgument;
            string[] strtemp = strArg.Split(',');
            int intID = int.Parse(strtemp[0]);
            int nRow = int.Parse(strtemp[1]);
            int nCol = int.Parse(strtemp[2]);
            int intTop = 50 + nRow * 120;
            int intLeft = 10 + nCol * 145;
            string strTop = intTop.ToString();
            string strLeft = intLeft.ToString();

            divComfirm.Style.Value = "position:absolute;left:" + strLeft + "px; top:" + strTop + "px; width:218px; height:114px; background-color:#ddeeff;";
            divComfirm.Visible = true;

            btnConfirm.CommandArgument = intID.ToString();

        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            divComfirm.Visible = false;
        }

        protected void btnConfirm_Click(object sender, EventArgs e)
        {
            Button btnSender = (Button)sender;
            string strID = btnSender.CommandArgument;

            DataTable dtLog = (DataTable)Session["dtOrg"];
            dtLog.DefaultView.RowFilter = "_id ='" + strID + "'";
            dtLog = dtLog.DefaultView.ToTable();

            if (Session["SysAdmin"].ToString() != "2")
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('你沒有修改設定的權限！')", true);
                return;
            }

            try
            {

                DataTable dtUser = new DBAccess().getUserData("1");
                dtUser.DefaultView.RowFilter = "_account= '" + Session["LoginAccount"].ToString() + "' and _password='" + tbPwd.Text + "'";
                dtUser = dtUser.DefaultView.ToTable();

                

                if (dtUser.Rows.Count > 0)
                {
                    DataTable dtOrg = (DataTable)Session["dtOrg"];

                    dtOrg.DefaultView.RowFilter = "_parent_id ='" + strID + "'";
                    DataTable dtRoom = dtOrg.DefaultView.ToTable();

                    DataTable dtDevice = DBAPI.getDeviceTable("1");
                    DataTable dtTag = DBAPI.getTagTable("1");

                    int intRelyTagID = 0;
                    string strErrMsg = "";

                    if (dtRoom!=null)
                    for (int nRoom = 0; nRoom < dtRoom.Rows.Count; nRoom++)
                    {

                        DataTable dtMeter = dtDevice.Copy();
                        

                        dtMeter.DefaultView.RowFilter = "_org_group_id ='" + dtRoom.Rows[nRoom]["_id"].ToString() + "'";
                        dtMeter = dtMeter.DefaultView.ToTable();

                        if (dtMeter != null)
                        for (int nMeter = 0; nMeter < dtMeter.Rows.Count; nMeter++)
                        {
                            DataTable dtTagCopy = dtTag.Copy();

                            dtTagCopy.DefaultView.RowFilter = "_controller_id ='" + dtMeter.Rows[nMeter]["_controller_id"].ToString() + "' and _device_id='" + dtMeter.Rows[nMeter]["_id"].ToString() + "'";
                            dtTagCopy = dtTagCopy.DefaultView.ToTable();

                            if (dtTagCopy != null)
                            for (int nTag = 0; nTag < dtTagCopy.Rows.Count; nTag++)
                            {
                                switch (dtTagCopy.Rows[nTag]["_name"].ToString())
                                {
                                    case "電表Reset":
                                        if (dtTagCopy.Rows[nTag]["_attribute"].ToString() == "AO")
                                            intRelyTagID = int.Parse(dtTagCopy.Rows[nTag]["_id"].ToString());
                                        break;

                                }
                            }

                            int intReset = 26214;

                            Boolean blnResult = WSAPI.SetTagValue(int.Parse(dtTagCopy.Rows[0]["_device_id"].ToString()), intRelyTagID, intReset);
                            if (blnResult == false)
                            {
                                strErrMsg = strErrMsg + dtMeter.Rows[nMeter]["_desc"].ToString() + "//";
                            }
                        }
                    }

                    string strAccount = Session["LoginAccount"].ToString();
                    string strIP = Session["LoginIP"].ToString();
                    string strMemo = "樓層名稱：" + dtLog.Rows[0]["_name"].ToString();

                    if (strErrMsg=="")
                    {
                        new DBAccess().addEventLog(strAccount, strIP, 103, strMemo, "1", int.Parse(strID));
                        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('樓層電錶歸零成功！')", true);
                        divComfirm.Visible = false;
                    }
                    else
                    {
                        new DBAccess().addEventLog(strAccount, strIP, 103, strMemo + "//以下電錶歸零失敗：" + strErrMsg, "0", int.Parse(strID));
                        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('樓層電錶歸零失敗！以下電錶歸零失敗" + strErrMsg + "')", true);
                    }

                }
                else
                {
                    string strAccount = Session["LoginAccount"].ToString();
                    string strIP = Session["LoginIP"].ToString();
                    string strMemo = "樓層名稱：" + dtLog.Rows[0]["_name"].ToString();
                    new DBAccess().addEventLog(strAccount, strIP, 103, strMemo, "0", int.Parse(strID));

                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('密碼認證錯誤！')", true);

                }

            }
            catch
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('樓層電錶歸零失敗！')", true);
            }

        }

    }
}